package org.csu.mypetstore.api.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
//import java.util.Base64;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

// JwtUtil.java
//@Component
//public class JwtTokenUtil {
////    private static final String SHARK="abcdefghigklmnopqrstuvwxyz123456";
//    private static final Key SHARK = Keys.secretKeyFor(SignatureAlgorithm.HS256);
//    public static String generateToken(String username){
//        Date now=new  Date();
//        int expire =3600000;//生效时间 一个小时
////        Date expiration=new Date(now.getTime()+1000*expire); //过期时间
//        long EXPIRATION_TIME = 3600000;
//        Date expiration=new Date(now.getTime()+EXPIRATION_TIME);
//        Map<String,String>map=new HashMap<>();
//        map.put("username",username);
//        ObjectMapper objectMapper = new ObjectMapper();
//        String subject = null;
//        try{
//            subject= objectMapper.writeValueAsString(map);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//        return Jwts.builder()
//                .setHeaderParam("type","Jwt")
//                .setSubject(subject)
//                .setIssuedAt(now)
//                .setExpiration(expiration)
//                .signWith(SHARK)
//                .compact();
////        return Jwts.builder()
////                .setHeaderParam("type","Jwt")
////                .setSubject(subject)
////                .setIssuedAt(now)
////                .setExpiration(expiration)
////                .signWith(SignatureAlgorithm.HS256, SHARK)
////                .compact();
//    }
//    //解析token
//    public static Claims getClaimsVyToken(String token) {
//        return Jwts.parser()
//                .setSigningKey(SHARK)
//                .parseClaimsJws(token)
//                .getBody();
//    }
//    // 解析用户名
//    public String getUsernameFromToken(String token) throws JsonProcessingException {
////        return Jwts.parser()
////                .setSigningKey(SHARK)
////                .parseClaimsJws(token)
////                .getBody()
////                .getSubject();
//
//        String subject=Jwts.parser()
//                .setSigningKey(SHARK)
//                .parseClaimsJws(token)
//                .getBody()
//                .getSubject();
//        //解析 JSON 格式的 subject
//        ObjectMapper objectMapper=new ObjectMapper();
//        Map<String,String>subjectMap=objectMapper.readValue(subject,Map.class);
//        return subjectMap.get("username");
//    }
//}




//2025.4.23.2:23
@Component
public class JwtTokenUtil {
    // 使用固定密钥（至少 256 位/32 字节）
    private static final String SECRET = "YourFixedSecretKeyAtLeast32BytesLong!";
    private static final Key SHARK = new SecretKeySpec(SECRET.getBytes(), SignatureAlgorithm.HS256.getJcaName());

    public static String generateToken(String username) {
        long nowMillis = System.currentTimeMillis();
        long expirationMillis = nowMillis + 3600 * 1000; // 1 小时

        Date now = new Date(nowMillis);
        Date expiration = new Date(expirationMillis);

        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        ObjectMapper objectMapper = new ObjectMapper();
        String subject;
        try {
            subject = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return Jwts.builder()
                .setHeaderParam("type", "Jwt")
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SHARK)
                .compact();
    }

    public static Claims getClaimsByToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SHARK)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public String getUsernameFromToken(String token) throws JsonProcessingException {
        String subject = Jwts.parserBuilder()
                .setSigningKey(SHARK)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> subjectMap = objectMapper.readValue(subject, new TypeReference<Map<String, String>>() {});
        return subjectMap.get("username");
    }
}